package cn.jimmie.learn.viewArt.ball;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

/**
 * function : 浮悬球视图 所依附的activity类的生命周期管理
 *
 * <p> Create Time: 2018年12月31日 16:38 </p>
 * <p> @author Jimmie.Qian  </p>
 */
class AssistLifeCycleManger implements Application.ActivityLifecycleCallbacks, View.OnLayoutChangeListener {
    private final Activity mActivity;
    private final View mAndroidContent;
    private OnLifeCycleCallbacks mListener;
    private boolean listening;

    AssistLifeCycleManger(Activity activity) {
        this.mActivity = activity;
        mAndroidContent = activity.findViewById(Window.ID_ANDROID_CONTENT);

        listening = true;
        // 监听屏幕尺寸变化
        mAndroidContent.addOnLayoutChangeListener(this);
        // 设置Activity生命周期监听
        activity.getApplication().registerActivityLifecycleCallbacks(this);
    }

    void register(OnLifeCycleCallbacks listener) {
        this.mListener = listener;
        if (listening) return;
        listening = true;
        // 监听屏幕尺寸变化
        mAndroidContent.addOnLayoutChangeListener(this);
        // 设置Activity生命周期监听
        mActivity.getApplication().registerActivityLifecycleCallbacks(this);
    }

    void unregister() {
        listening = false;
        mListener = null;
        mAndroidContent.removeOnLayoutChangeListener(this);
        mActivity.getApplication().unregisterActivityLifecycleCallbacks(this);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (mListener == null || activity != this.mActivity) return;
        mListener.onActivityStart(activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
    }

    @Override
    public void onActivityPaused(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (mListener == null || activity != this.mActivity) return;
        mListener.onActivityStop(activity);
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (mListener == null || activity != this.mActivity) return;
        mListener.onActivityDestroy(activity);
        unregister();
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (mListener == null || mActivity.isFinishing()) return;
        mListener.onLayoutChanged(right - left, bottom - top);
    }

    public interface OnLifeCycleCallbacks extends OnScreenChangedObserver {

        void onActivityStart(Activity activity);

        void onActivityStop(Activity activity);

        void onActivityDestroy(Activity activity);
    }
}
